<template>
  <view class="container">
    <!-- 自定义顶部导航栏 -->
    <view class="custom-app-bar-wrapper" :style="{ height: `calc(100rpx + ${statusBarHeight}px)` }">
      <view class="custom-app-bar" :style="{ top: statusBarHeight + 'px' }">
        <u-icon name="arrow-left" size="40" class="back-icon" @click="goBack"></u-icon>
        <text class="title">创建计划</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-wrapper" :style="{ paddingTop: `calc(100rpx + ${statusBarHeight}px)` }">
      <u-form :model="form" ref="uForm" label-position="top">
        <u-form-item label="计划名称" prop="name">
          <u-input v-model="form.name"></u-input>
        </u-form-item>

        <u-form-item label="计划类型" prop="planType">
          <u-radio-group v-model="form.planType">
            <u-radio :name="1">绘本集计划</u-radio>
            <u-radio :name="2">自定义计划</u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="每天学几个新的" prop="learnAFewNewThingsEveryDay" v-if="form.planType === 1">
          <u-number-box v-model="form.learnAFewNewThingsEveryDay" :min="1" :max="10"></u-number-box>
        </u-form-item>
        <u-form-item label="复习次数" prop="reviewFrequency" v-if="form.planType === 1">
          <view class="select-box" @click="showReviewPicker = true">
            <text>{{ reviewOptions[form.reviewFrequency - 1] || '请选择复习次数' }}</text>
            <u-icon name="arrow-down-fill" size="24" color="#999"></u-icon>
          </view>
        </u-form-item>
        <u-form-item label="绘本集" prop="bookShelfIds" v-if="form.planType === 1">
          <view class="bookshelf-selection">
            <u-button type="primary" size="medium" shape="circle" @click="selectBookShelf">
              {{ selectedBookShelves.length > 0 ? `已选择${selectedBookShelves.length}个绘本集` : '添加绘本集' }}
            </u-button>
            <view class="selected-bookshelves" v-if="selectedBookShelves.length > 0">
              <view class="bookshelf-tag" v-for="item in selectedBookShelves" :key="item.id">
                {{ item.title }}
              </view>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="自定义计划" prop="bookReadingProgramItemRespVOList" v-if="form.planType === 2">
          <view class="custom-plan-container">
            <!-- 天数列表 -->
            <view class="day-list" v-if="form.bookReadingProgramItemRespVOList.length > 0">
              <view class="day-item" v-for="(dayItem, index) in form.bookReadingProgramItemRespVOList" :key="index">
                <view class="day-header">
                  <text class="day-title">第{{ index + 1 }}天</text>
                  <view class="day-actions" v-if="dayItem.selectedBooks && dayItem.selectedBooks.length > 0">
                    <text class="book-count">已选{{ dayItem.selectedBooks.length }}本</text>
                    <u-icon name="trash" size="20" color="#ff4757" @click="clearDayBooks(index)"></u-icon>
                  </view>
                </view>
                <view class="day-books">
                  <!-- 已选择的书籍 -->
                  <view class="book-item" v-for="book in dayItem.selectedBooks" :key="book.id">
                    <image class="book-cover" :src="getBookCoverUrl(book)" mode="aspectFit"></image>
                    <text class="book-name">{{ book.bookName }}</text>
                  </view>
                  <!-- 添加书籍按钮 -->
                  <view class="add-book-btn" @click="selectBooksForDay(index)">
                    <u-icon name="plus" size="24" color="#999"></u-icon>
                  </view>
                </view>
              </view>
            </view>
            <!-- 增加一天按钮 -->
            <u-button type="info" size="medium" shape="circle" @click="addDay" class="add-day-btn">
              增加一天
            </u-button>
          </view>
        </u-form-item>
      </u-form>
      <text class="tips">*预计每天最多阅读{{ form.learnAFewNewThingsEveryDay * 2 }}本</text>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-bar">
      <u-button type="primary" shape="circle" @click="save" :loading="loading" :disabled="loading">
        {{ loading ? '创建中...' : '保存并预览' }}
      </u-button>
    </view>

    <!-- 复习次数选择器 -->
    <u-select v-model="showReviewPicker" :list="reviewPickerList" @confirm="onReviewConfirm"></u-select>
  </view>
</template>

<script>
import * as BookRecordApi from '@/api/bookRecord'
import * as BookShelfApi from '@/api/bookShelf'
import UInput from "../../uview-ui/components/u-input/u-input.vue";

export default {
  components: {UInput},
  data() {
    return {
      type: '',
      statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
      form: {
        name:'',
        catalogue:'',
        planType: 1, // 计划类型：1-绘本集计划，2-自定义计划
        learnAFewNewThingsEveryDay: 1, // 每天学几个新的
        reviewFrequency: 1, // 复习次数
        bookShelfIds: '', // 绘本集ID
        bookReadingProgramItemRespVOList: [] // 自定义计划项目列表
      },
      showReviewPicker: false,
      reviewOptions: ['1次（第2天）', '2次（第2、4天）', '3次（第2、4、7天）'],
      reviewPickerList: [{
        value: 1,
        label: '1次（第2天）'
      }, {
        value: 2,
        label: '2次（第2、4天）'
      }, {
        value: 3,
        label: '3次（第2、4、7天）'
      }],
      bookShelfList: [], // 绘本集列表
      selectedBookShelves: [], // 已选择的绘本集
      showBookShelfPicker: false,
      loading: false
    };
  },
  onLoad(options) {
    this.type = options.type || ''; // 获取type参数，如果没有则默认为空
    console.log('接收到的type参数:', this.type);
  },
  methods: {


    goBack() {
      uni.navigateBack();
    },

    onReviewConfirm(e) {
      this.form.reviewFrequency = e[0].value;
    },

    // 选择绘本集
    selectBookShelf() {
      // 跳转到绘本集选择页面
      uni.navigateTo({
        url: '/pages/plan/select-bookshelf?type=' + this.type,
        events: {
          // 监听绘本集选择结果
          selectBookShelf: (data) => {
            this.form.bookShelfIds = data.bookShelfIds;
            this.selectedBookShelves = data.selectedBookShelves;
          }
        }
      });
    },

    // 保存计划
    async save() {
      if (!this.validateForm()) {
        return;
      }

      this.loading = true;
      try {
        const params = {
          planType: this.form.planType
        };

        // 绘本集计划才需要这些字段
        if (this.form.planType === 1) {
          params.learnAFewNewThingsEveryDay = this.form.learnAFewNewThingsEveryDay;
          params.reviewFrequency = this.form.reviewFrequency;
        }

        if (this.form.planType === 1) {
          // 绘本集计划
          params.bookShelfIds = this.form.bookShelfIds;
        } else {
          // 自定义计划
          params.bookReadingProgramItemRespVOList = this.form.bookReadingProgramItemRespVOList.map((day, index) => ({
            bookIds: day.bookIds || '',
            days: (index + 1).toString()
          }));
        }
        params.name = this.form.name;
        params.catalogue = this.type;

        const response = await BookRecordApi.createBookReadingProgram(params);
        if (response.code === 0) {
          uni.showToast({
            title: '计划创建成功',
            icon: 'success'
          });
          // 回到上一级页面
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: response.msg || '创建失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('创建计划失败:', error);
        uni.showToast({
          title: '创建计划失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 增加一天
    addDay() {
      this.form.bookReadingProgramItemRespVOList.push({
        days: (this.form.bookReadingProgramItemRespVOList.length + 1).toString(),
        bookIds: '',
        selectedBooks: []
      });
    },

    // 为某一天选择书籍
    selectBooksForDay(dayIndex) {
      console.log('selectBooksForDay called with dayIndex:', dayIndex);
      uni.showToast({
        title: '正在跳转到书籍选择页面...',
        icon: 'none'
      });

      // 跳转到绘本集和书籍选择页面
      uni.navigateTo({
        url: '/pages/plan/select-books?dayIndex=' + dayIndex + '&type=' + this.type,
        events: {
          // 监听书籍选择结果
          selectBooks: (data) => {
            console.log('selectBooks event received:', data);
            const dayItem = this.form.bookReadingProgramItemRespVOList[dayIndex];

            // 拼接书籍ID（避免重复）
            const existingBookIds = dayItem.bookIds ? dayItem.bookIds.split('_') : [];
            const newBookIds = data.bookIds.split('_');
            const allBookIds = [...existingBookIds];

            newBookIds.forEach(bookId => {
              if (!allBookIds.includes(bookId)) {
                allBookIds.push(bookId);
              }
            });

            dayItem.bookIds = allBookIds.join('_');

            // 拼接选择的书籍（避免重复）
            const existingBooks = dayItem.selectedBooks || [];
            const newBooks = data.selectedBooks || [];
            const allBooks = [...existingBooks];

            newBooks.forEach(newBook => {
              const exists = allBooks.some(book => book.id === newBook.id);
              if (!exists) {
                allBooks.push(newBook);
              }
            });

            dayItem.selectedBooks = allBooks;

            uni.showToast({
              title: `书籍选择成功，共${allBooks.length}本`,
              icon: 'success'
            });
          }
        },
        success: function (res) {
          console.log('navigateTo success');
          // 通过 eventChannel 向被打开页面传送数据
          res.eventChannel.emit('acceptDataFromOpenerPage', {dayIndex: dayIndex})
        },
        fail: function (err) {
          console.error('navigateTo failed:', err);
          uni.showToast({
            title: '跳转失败，请重试',
            icon: 'none'
          });
        }
      });
    },

    // 获取书籍封面URL
    getBookCoverUrl(book) {
      if (book.coverUrl) {
        return book.coverUrl;
      }
      if (book.url && book.url.trim()) {
        // 处理逗号分隔的图片名称，取第一张
        const imageNames = book.url.split(',');
        if (imageNames.length > 0 && imageNames[0].trim()) {
          return `/static/url/${imageNames[0].trim()}`;
        }
      }
      // url为空时默认显示defualt_1.png
      return '/static/url/defualt_1.png';
    },

    // 清空某一天的书籍选择
    clearDayBooks(dayIndex) {
      uni.showModal({
        title: '确认清空',
        content: `确定要清空第${dayIndex + 1}天的所有书籍选择吗？`,
        success: (res) => {
          if (res.confirm) {
            const dayItem = this.form.bookReadingProgramItemRespVOList[dayIndex];
            dayItem.bookIds = '';
            dayItem.selectedBooks = [];
            uni.showToast({
              title: '已清空',
              icon: 'success'
            });
          }
        }
      });
    },

    // 表单验证
    validateForm() {
      // 绘本集计划的验证
      if (this.form.planType === 1) {
        if (!this.form.learnAFewNewThingsEveryDay) {
          uni.showToast({
            title: '请输入每天学几个新的',
            icon: 'none'
          });
          return false;
        }
        if (!this.form.reviewFrequency) {
          uni.showToast({
            title: '请选择复习次数',
            icon: 'none'
          });
          return false;
        }
        if (!this.form.bookShelfIds) {
          uni.showToast({
            title: '请选择绘本集',
            icon: 'none'
          });
          return false;
        }
        if (this.form.learnAFewNewThingsEveryDay < 1) {
          uni.showToast({
            title: '每天学习数量不能少于1个',
            icon: 'none'
          });
          return false;
        }
      }

      // 自定义计划的验证
      if (this.form.planType === 2) {
        if (this.form.bookReadingProgramItemRespVOList.length === 0) {
          uni.showToast({
            title: '请至少添加一天的计划',
            icon: 'none'
          });
          return false;
        }
      }

      return true;
    }
  }
};
</script>

<style lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f7f7;
}

.custom-app-bar-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff; // 状态栏区域的背景色
}

.custom-app-bar {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100rpx;
  padding: 0 20rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.back-icon {
  position: absolute;
  left: 20rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.form-wrapper {
  /* margin-top: 100rpx; */
  // 留出导航栏空间
  padding: 30rpx;
  background-color: #fff;
  flex: 1;
}

.select-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  width: 100%;
}

.tips {
  display: block;
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.footer-bar {
  padding: 20rpx;
  background-color: #fff;
}

.bookshelf-selection {
  width: 100%;
}

.selected-bookshelves {
  margin-top: 20rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.bookshelf-tag {
  padding: 8rpx 16rpx;
  background-color: #f0f9ff;
  color: #0369a1;
  border-radius: 20rpx;
  font-size: 24rpx;
  border: 1rpx solid #bae6fd;
}

.custom-plan-container {
  width: 100%;
}

.day-list {
  margin-bottom: 20rpx;
}

.day-item {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  border-left: 4rpx solid #007aff;
}

.day-header {
  margin-bottom: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.day-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.day-actions {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.book-count {
  font-size: 24rpx;
  color: #007aff;
  background-color: rgba(0, 122, 255, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.day-books {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  align-items: center;
}

.book-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120rpx;
}

.book-cover {
  width: 80rpx;
  height: 100rpx;
  border-radius: 8rpx;
  margin-bottom: 8rpx;
  background-color: #e5e5e5;
}

.book-name {
  font-size: 22rpx;
  color: #666;
  text-align: center;
  max-width: 120rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.add-book-btn {
  width: 120rpx;
  height: 120rpx;
  border: 2rpx dashed #ccc;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  gap: 6rpx;
  padding: 8rpx;
  box-sizing: border-box;
}

.add-book-text {
  font-size: 20rpx;
  color: #999;
  text-align: center;
}

.add-day-btn {
  width: 100%;
  margin-top: 20rpx;
}
</style>
